/*
 *   项目名称：rpc-demo
 *   文件名称：com.xiaolon.rpc.loadbalancer.RandomLoadBalancer
 *
 *   创建人：  ZHOU XIAO LONG
 *   创建日期：2024/12/11
 *
 */
package com.xiaolon.rpc.loadbalancer;

import com.xiaolon.rpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.Random;

/*
 * 类描述：RandomLoadBalancer
 * 随机负载均衡器
 */
public class RandomLoadBalancer implements LoadBalancer{

    private final Random random = new Random();

    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        int size = serviceMetaInfoList.size();
        if(size == 0){
            return null;
        }

        // 只有一个服务, 不用随机
        if(size == 1) return serviceMetaInfoList.get(0);

        return serviceMetaInfoList.get(random.nextInt(size));
    }
}
